package club.mzywucai.blog.air_portal.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 * @author
 * 
 */
public class MD5Util {

	public static void main(String[] args) {
		String s = "/document/2019/2/11/086bf2a2-e96e-4da6-8657-94f54a5835da.pdf";
		System.out.println(md5(s));
	}

	/**
	 * md5加密
	 * 
	 * @param str
	 * @return
	 */
	private static String md5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] byteDigest = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < byteDigest.length; offset++) {
				i = byteDigest[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			// 32位加密
			return buf.toString();
			// 16位的加密
			// return buf.toString().substring(8, 24);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}


	public static boolean checkPass(String str, String passFormDb) {
		String random = passFormDb.substring(0, 2);

		String pass = random + str;
		String s = md5(pass);

		String newPass = random + s;
		if (newPass.equals(passFormDb.toLowerCase())) {
			return true;
		}

		return false;
	}

	public static String changePass(String str) {
		String randString = "";
		for (int i = 0; i<2; i++){
			randString = randString + (char)(Math.random()*26+'a');
		}

		String s = randString + str;
		String pass = md5(s);
		String passEnd = randString + pass;

		return passEnd;
	}

}
